'''
平安e生保
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "平安e生保"

    # 生成产品数据
    def genProductInfo(self):
        plan = [{

            "plan": "100万有社保版",
            "generalMedical": "100w",
            "seriousMedical": "100w",
            "packageCode":"PK00018288",
            "introduce": {
                "国内第二诊疗意见（1次）当": "专项",
                "就医绿色通道（1次）": "专项"
            }
        }, {

            "plan": "100万无社保版",
            "generalMedical": "100w",
            "seriousMedical": "100w",
            "packageCode":"PK00018289",
            "introduce": {
                "国内第二诊疗意见（1次）当": "专项",
                "就医绿色通道（1次）": "专项"
            }
        }, {

            "plan": "300万有社保版",
            "generalMedical": "300w",
            "seriousMedical": "300w",
            "packageCode":"PK00018290",
            "introduce": {
                "国内第二诊疗意见（1次）当": "专项",
                "就医绿色通道（1次）": "专项"
            }
        }, {

            "plan": "300万无社保版",
            "generalMedical": "300w",
            "seriousMedical": "300w",
            "packageCode":"PK00018291",
            "introduce": {
                "国内第二诊疗意见（1次）当": "专项",
                "就医绿色通道（1次）": "专项"
            }
        }

        ]

        years = [str(i) for i in range(0, 61)]
        for v in product(years, plan):
            year = v[0]
            plan = v[1]["plan"]
            packageCode = v[1]["packageCode"]
            generalMedical = v[1]["generalMedical"]
            seriousMedical = v[1]["seriousMedical"]
            introduce = "'" + json.dumps(v[1]["introduce"], ensure_ascii=False) + "'"

            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                year, plan, packageCode,generalMedical, seriousMedical, introduce

            ))

            self.mysql._conn.commit()

            print(domain[self.name]["insert_sql"].format(

                year, plan,packageCode, generalMedical, seriousMedical, introduce

            ))

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {"flowId": "A0MzuN03su5rDIAH",
                "planPackage": {"packageCode": "PK00018290", "marketProductCode": "MP03000599", "packageType": "01"},
                "insurantNum": [{"personNum": "1", "subjectType": "02"}], "applyPeriod": {"term": 12, "termUnit": "M"},
                "effectDate": {"beginDate": "2020-01-04", "endDate": "2021-01-03",
                               "birthDay": "{0}-01-24".format(str(2019 - int(dt["year"])))},
                "addDays": ""}

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=json.dumps(data))


        if r.status_code == 200:

            for item in (r.json()["quoteResult"]):

                #根据年龄选择数据
                YEAR_SQL = "SELECT * FROM `平安e生保` WHERE year = {0} and state = 0 and packageCode = '{1}'".format( dt["year"],item["packageCode"])

                self.mysql.cursor.execute( YEAR_SQL  )

                result = self.mysql.cursor.fetchone()

                #执行更新
                data = {

                    "name":self.name,
                    "id":result["id"],
                    "price":Helper.decimalParse(item["actualPremium"])
                }

                self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

            print("产品价格更新失败:", dt["id"])



    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            # data = {
            #     "name": self.name,
            #     "id": dt["id"],
            #     "state": 1
            # }
            # self.mysql.updateTask(data)

            self.requestJson(dt)

    def test(self,null=None,false=None,true=None):

        data = {
            "saleInfoForm": null,
            "umsProductInfo": null,
            "petTypeFlag": null,
            "mobileInfoForm": null,
            "insurant": null,
            "renewalFlag": null,
            "originalInsurant": null,
            "roadTransferForm": null,
            "petInfoForm": null,
            "security": null,
            "planDuty": null,
            "resultMsg": "处理成功",
            "internationalFlightDelayInfoForm": null,
            "planPackage": {
                "dutyList": [{
                    "amount": "3000000",
                    "amountText": null,
                    "amountUnit": "元",
                    "dutyCode": "CVJA041",
                    "dutyName": "一般医疗保险金",
                    "dutyType": null,
                    "ensureRange": null,
                    "planCode": "PL03J0140",
                    "planId": "8F18E7DA67FE57BEE054022128574717",
                    "planName": "平安意外伤害医疗和疾病医疗保险（平安e生保款）",
                    "subjectType": "02",
                    "typeCode": "t_heath",
                    "typeName": "健康保障"
                }, {
                    "amount": "3000000",
                    "amountText": null,
                    "amountUnit": "元",
                    "dutyCode": "CVJA042",
                    "dutyName": "恶性肿瘤医疗保险金",
                    "dutyType": null,
                    "ensureRange": null,
                    "planCode": "PL03J0140",
                    "planId": "8F18E7DA67FF57BEE054022128574717",
                    "planName": "平安意外伤害医疗和疾病医疗保险（平安e生保款）",
                    "subjectType": "02",
                    "typeCode": "t_heath",
                    "typeName": "健康保障"
                }],
                "marketProductCode": "MP03000599",
                "packageCode": "PK00018291",
                "packageName": "300万无社保版",
                "packageType": "01"
            },
            "applyPattern": null,
            "planType": null,
            "visaType": null,
            "annualForm": null,
            "professionType": null,
            "resultCode": "Z0101001",
            "applyPeriod": {
                "term": 12,
                "termUnit": "M"
            },
            "carsTolen": null,
            "couponCodeForm": null,
            "insurantNum": [{
                "personNum": 1,
                "subjectType": "02",
                "propsNum": null
            }],
            "groupRiskPropertyForm": null,
            "carsTolenGoodsForm": null,
            "professionCode": null,
            "effectDate": {
                "addDays": null,
                "endDate": "2021-01-03",
                "birthDay": "1998-01-24",
                "beginDateFixed": false,
                "beginDate": "2020-01-04"
            },
            "sicsQuoteForm": null,
            "microQuoteForm": null,
            "microSaleInfoForm": null,
            "quoteResult": [{
                "actualPremium": 249.0,
                "actualPremiumText": "会员价",
                "couponAmount": null,
                "marketProductCode": "MP03000599",
                "memberPremium": 249.0,
                "memberPremiumText": "会员价",
                "orginalPremium": 249.0,
                "originalPremiumText": "原价",
                "packageCode": "PK00018288",
                "selected": false,
                "voucherAmount": null
            }, {
                "actualPremium": 474.0,
                "actualPremiumText": "会员价",
                "couponAmount": null,
                "marketProductCode": "MP03000599",
                "memberPremium": 474.0,
                "memberPremiumText": "会员价",
                "orginalPremium": 474.0,
                "originalPremiumText": "原价",
                "packageCode": "PK00018289",
                "selected": false,
                "voucherAmount": null
            }, {
                "actualPremium": 271.0,
                "actualPremiumText": "会员价",
                "couponAmount": null,
                "marketProductCode": "MP03000599",
                "memberPremium": 271.0,
                "memberPremiumText": "会员价",
                "orginalPremium": 271.0,
                "originalPremiumText": "原价",
                "packageCode": "PK00018290",
                "selected": false,
                "voucherAmount": null
            }, {
                "actualPremium": 518.0,
                "actualPremiumText": "会员价",
                "couponAmount": null,
                "marketProductCode": "MP03000599",
                "memberPremium": 518.0,
                "memberPremiumText": "会员价",
                "orginalPremium": 518.0,
                "originalPremiumText": "原价",
                "packageCode": "PK00018291",
                "selected": true,
                "voucherAmount": null
            }],
            "applyNum": null,
            "travelDestinations": null,
            "houseInfoForm": null,
            "applicant": null,
            "sendDetail": null,
            "planSex": null,
            "flowId": "B0MzgXAacEcMKcji"
        }

        for item in ( data["quoteResult"]):

            print( item )



if __name__ == '__main__':
    s = Spider()
    s.main()

